package com.test.cities.page;

import com.test.cities.Exceptions.Asserts;
import com.test.cities.Exceptions.BusinessException;
import com.test.cities.entity.Bag;
import com.test.cities.entity.Box;
import com.test.cities.entity.BoxLabel;
import com.test.cities.entity.Stock;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.query.Query;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

@Component
public class AppleShop {

    StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
            .configure("hibernate.cfg.xml")
            .build();
    SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
    Session session = sessionFactory.openSession();
    private List<Box> boxes;

    private HashMap<Long, String> bagContent = new HashMap<>();

    public void stock(List<Stock> stockList) throws BusinessException {
        Transaction t=session.beginTransaction();

        for (Stock snakeApple : stockList) {
//            Asserts.isTrue(snakeApple.getNo()==0, "苹果编号不能为0");
            session.persist(snakeApple);
        }

        t.commit();
        System.out.println("入库苹果成功");

    }

    public void sort(){
        Transaction t=session.beginTransaction();

//        returnBox();

        String sql = "Select e from " + Stock.class.getName() + " e " + " order by e.no NULLS LAST";
        Query<Stock> query= session.createQuery(sql);
        List<Stock> resultList = query.getResultList();

        t.commit();

        for (Stock stock : resultList) {
            System.out.println("库存苹果:" + stock.getNo() + ":" + stock.getName() + ":" + stock.getGood());
        }
    }

    public void returnBox() {
        Transaction t=session.beginTransaction();
        Query query = session.createQuery("delete from "+Box.class.getName());
        query.executeUpdate();
        t.commit();
    }

    public void sell(List<Long> sellList){

        Transaction t=session.beginTransaction();

        Integer num = 0;
        boxes = new ArrayList<>();

        for (Long sellNo : sellList) {
            String sql = "Select e from " + Stock.class.getName() + " e " + " where e.no=:Eno ";
            Query<Stock> query = session.createQuery(sql);
            query.setParameter("Eno", sellNo);
            Stock stock = query.getSingleResult();
            if (stock == null) {
                System.out.println("苹果不存在"+sellNo);
                continue;
            }else {
                num++;
            }
            Box box = new Box();
            box.setNo(stock.getNo());
            box.setName(stock.getName());
            box.setGood(stock.getGood());
            box.setSellDate(LocalDate.now());
            boxes.add(box);
        }

        String boxLabel = boxLabelGenerate(num);
        BoxLabel label = new BoxLabel();
        label.setBoxLabel(boxLabel);
        session.persist(label);
        System.out.println("已售出-箱子编号:" + boxLabel);
        for (Box box : boxes) {
            System.out.println("售出苹果:" + box.getName() + "-" + box.getNo());
        }
        System.out.println("--------");

        for (Box box : boxes) {
            Long no = box.getNo();
            session.persist(box);

            Query query = session.createQuery("delete from "+Stock.class.getName()+" where no=:Eno");
            query.setParameter("Eno", no);
            query.executeUpdate();
        }

        t.commit();
    }

    private String boxLabelGenerate(Integer num) {

        String year = "" + LocalDate.now().getYear();
        String monthDay = LocalDate.now().format(DateTimeFormatter.ofPattern("MMdd"));
        String numstring = num.toString();

        return year + monthDay + "-" + numstring;
    }

    public void close(){
        Transaction t=session.beginTransaction();

        String sql = "Select e from " + Stock.class.getName() + " e " + " where e.good=:Good";

        Query<Stock> query= session.createQuery(sql);
        query.setParameter("Good", "坏了");

        List<Stock> resultList = query.getResultList();

        int num = 0;

        for (Stock stock : resultList) {
            num++;
            stock.setAppleLabel("bad:"+stock.getNo());
            //TODO 优化
            bagContent.put(stock.getNo(),stock.getName());
            Bag bagList = new Bag();
            BeanUtils.copyProperties(stock,bagList);
            session.merge(bagList);

            Long removeNo = stock.getNo();
            Query deleteQuery = session.createQuery("delete from "+Stock.class.getName()+" where no=:Eno");
            deleteQuery.setParameter("Eno", removeNo);
            deleteQuery.executeUpdate();
        }

        t.commit();
        System.out.println("坏掉苹果有"+num+"个");
        Collection<String> badApples = bagContent.values();
        badApples.forEach(value-> System.out.println("报废苹果:"+value));

    }


}
